package cn.tedu.charging.order.amqp;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 将rabbitmq的客户端包装,给业务提供所需方法
 */
@Component
@Slf4j
public class AmqpProducerClient {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //包装延迟消息发送 序列化依然使用json
    public void sendDelay(String target,Object msg,long ttl){
        this.sendDelay(target,null,msg,ttl);
    }
    //重载方法 提供路由key值
    public void sendDelay(String target,String routingKey,Object msg,long ttl){
        log.info("开始发送延迟消息");
        //1.封装消息对象message
        MessageProperties props=new MessageProperties();
        props.setExpiration(String.valueOf(ttl));
        props.setContentType("UTF-8");
        //2.msg做序列化 json->byte[]
        String json= JSON.toJSONString(msg);
        byte[] body=json.getBytes(StandardCharsets.UTF_8);
        //3.message封装
        Message message=new Message(body,props);
        //4.发送
        rabbitTemplate.send(target,routingKey,message);
    }
}
